package com.dididoctor.patient.Activity.Doctor.Doctordetail;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.AbsListView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.dididoctor.patient.Activity.ConstantValue;
import com.dididoctor.patient.Activity.Inquiry.InquiryActivity;
import com.dididoctor.patient.Activity.MakeCall.MakeCallActivity;
import com.dididoctor.patient.Activity.Usercentre.Consume.UserConsumeActivity;
import com.dididoctor.patient.Bean.DiaeasesLitapal;
import com.dididoctor.patient.Bean.Token;
import com.dididoctor.patient.Dialog.DiseaseListDialog;
import com.dididoctor.patient.MV.EduActivity;
import com.dididoctor.patient.R;
import com.dididoctor.patient.Ui.customlistview.OnRefreshListener;
import com.dididoctor.patient.Ui.customlistview.RefreshListView;
import com.dididoctor.patient.Utils.LoaderImage;
import com.dididoctor.patient.Utils.SharedPreferencesUtils;
import com.dididoctor.patient.Utils.UserHeadImage;
import com.dididoctor.patient.Utils.Util;
import com.dididoctor.patient.WYY.SessionHelper;
import com.dididoctor.patient.ZFB.PayResult;
import com.dididoctor.patient.ZFB.SignUtils;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;


/**
 * @version 2.0
 * @类描述：
 * @项目名称：ddgh
 * @类名称： DoctorDetailActivity
 * @包名称： com.dididoctor.doctor.Activity.docter.doctordetail
 * @创建人： zhanjunjie
 * @创建时间：2016/4/1 10:06
 * @修改人：
 * @修改时间：2016/4/1 10:06
 * @修改备注： new parent class(用一句话描述修改了什么)
 */
public class DoctorDetailActivity extends EduActivity implements DoctorDetailView {
    private TextView mTvName, mTvSignnum, mTvAddress, mTvEvaluate, mTvDist, mTvSign, mTvCollect, mTvIsDoctor, mTvIsCall, mTvPrdName, mTvPrdPirce;
    private ImageView mImgCollect, mImgSign, mImgCall;
    private UserHeadImage headImage;
    private UserHeadImage isonlie;
    private LoaderImage loaderImage;
    private RefreshListView listView;
    private LinearLayout mLlNoEvaluate;
    private RelativeLayout mRlPay, rel_sign;
    private WebView webview;

    //数据
    private List<DoctorEvaluate> evaluates = new ArrayList<DoctorEvaluate>();
    private DoctorDetailPresenter presenter;
    private DoctorDetailAdapter adapter;
    private DoctorDetail doctorDetail = new DoctorDetail();
    private Prdetail prdetail = new Prdetail();
    private Prdbuy prdbuy = new Prdbuy();
    private Timer timer = new Timer();

    //跳转数据
    private String hospitalId = "", longitude = "", latitude = "", accId = "";

    //接口数据
    private String ptype = "", type = "2", recId = "", doctorId = "";
    private boolean isprice = false;
    private boolean iscollect = false;
    //微信支付
    private IWXAPI api;
    private String zqtype;
    private String prdId;
    private String alltotal_fee;
    private List<DiaeasesLitapal> litapals = new ArrayList<>();

    // 商户PID
    public static final String PARTNER = "";
    // 商户收款账号
    public static final String SELLER = "";
    private LinearLayout mLinImgortext;
    // 商户私钥，pkcs8格式
    public static final String RSA_PRIVATE = "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAL5AypQkeMlT97sa\n" +
            "+B9KnLxnNSFS9jmkmG57grcfiznoZpne2VqTrgZA2WvU3vHIoS6P6dMCbLRBQrz1\n" +
            "PyYg1tfq1w/HGb5RSYkjYCCeYXdqsVG1TcvveWsczcuTZWv7+OC/lGnEZOvn6KMr\n" +
            "Cp1n2X3JQJsCfiDxILW4+WbvnKUxAgMBAAECgYAp0Un1t/KIphksmifxkM/UpYbL\n" +
            "FVYjo2cR2boIkDlk+A0dQxtZSl6U50oi5n4+fM/Y0S8e/0hvcmy95dYEhnFSUOx1\n" +
            "MJMU/fQJaduy4av5dugFTp4Kj7UfbQXT5ys0wBY5TsA708j7Gn/L8OwdtWpwgsWP\n" +
            "bw5hAu5ydTCL4SCwtQJBAO7n6Zg7solE+mXiYybfaGtHWrH01wd3WbAs/cgyG5L4\n" +
            "6Z2oBdys0XjMLeqAJWqXSX4+SclYNx5H2AyMG6LS5/cCQQDL3bIG+6lFzgKPQ+Xt\n" +
            "GvaLzQ46rpzVrGOGzRwdAE+ffPIxRLj+ykSP3bLafsygQdUWNVX+Kt7V0xnaywCq\n" +
            "PSIXAkEArDiqgH+oeKQtDf1hFMjAcXWCv/6MdGlpUkNcv1C/5/dgEbLqZuZ+KuKl\n" +
            "xwKR9oERDdzBPFBHi6Cm8oSd94aqiQJAQQqpGts9xTyVynmCKOSaVj4E1SoSdYV7\n" +
            "d22HE6WewaaOarOfRgLoXvH/dwBPbq2yO1Sm6+FnmNayAAEWZDn+3wJBAN/zOQzB\n" +
            "TAk4GT1MIE8mRRCFxSZYQmc5oRYpl4dp+ymcDdEB8LJsK+0o/phA+6nm/mS6vLjD\n" +
            "eda6qHepXLN43eU=\n";
    // 支付宝公钥
    public static final String RSA_PUBLIC = "";
    private static final int SDK_PAY_FLAG = 1;

    //接收支付成功广播
    private PayOkRecedir myReceiver;

    @Override
    public void init() {
        api = WXAPIFactory.createWXAPI(this, ConstantValue.APP_ID, false);
        api.registerApp(ConstantValue.APP_ID);
        initview();

        initdata();

        //24z中小病
        litapals = DiaeasesLitapal.getdisarases();
        initmyBroadcast();
    }

    private void initmyBroadcast() {
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("PayOkRecedir");
        myReceiver = new PayOkRecedir();
        registerReceiver(myReceiver, intentFilter);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        try {
            unregisterReceiver(myReceiver);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void initdata() {
        hospitalId = getIntent().getStringExtra("hospitalId");
        longitude = getIntent().getStringExtra("longitude");
        latitude = getIntent().getStringExtra("latitude");
        adapter = new DoctorDetailAdapter(this, evaluates);
        listView.setAdapter(adapter);
        listView.setHeadAndFoot(false, false);
        listView.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onPullDownRefresh() {
                listView.onRefreshFinish();
            }

            @Override
            public void onLoadMoring() {
                listView.onRefreshFinish();
            }

            @Override
            public void onScrollListener(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

            }
        });
        presenter = new DoctorDetailPresenter(this, this);
//        presenter.getdoctordetail(hospitalId, longitude, latitude);
    }

    @Override
    protected void onResume() {
        super.onResume();
        presenter.getdoctordetail(hospitalId, longitude, latitude);
    }

    private void initview() {
        ((TextView) findViewById(R.id.tv_title)).setText("医生详情");
        mTvName = (TextView) findViewById(R.id.tv_nameorjbo);
        mTvSignnum = (TextView) findViewById(R.id.tv_signnum);
        mTvAddress = (TextView) findViewById(R.id.tv_address);
        mTvEvaluate = (TextView) findViewById(R.id.tv_evaluate);
        mTvDist = (TextView) findViewById(R.id.tv_distance);
        mTvSign = (TextView) findViewById(R.id.tv_sgin);
        mTvCollect = (TextView) findViewById(R.id.tv_collect);
        mTvIsDoctor = (TextView) findViewById(R.id.tv_isdoctor);
        mTvIsCall = (TextView) findViewById(R.id.tv_iscall);
        mImgCollect = (ImageView) findViewById(R.id.img_collect);
        mImgSign = (ImageView) findViewById(R.id.img_sign);
        mImgCall = (ImageView) findViewById(R.id.img_call);
        mImgCall.setOnClickListener(this);
        mTvPrdName = (TextView) findViewById(R.id.tv_prdname);
        mTvPrdPirce = (TextView) findViewById(R.id.tv_prdprice);
        mRlPay = (RelativeLayout) findViewById(R.id.rel_zifufangsi);
        mRlPay.setOnClickListener(this);
        rel_sign = (RelativeLayout) findViewById(R.id.rel_sign);
        rel_sign.setOnClickListener(this);
        mLlNoEvaluate = (LinearLayout) findViewById(R.id.ll_no_evaluate);
        mImgCall.setOnClickListener(this);
        webview = (WebView) findViewById(R.id.webview);
        headImage = (UserHeadImage) findViewById(R.id.img_user);
        isonlie = (UserHeadImage) findViewById(R.id.img_isonlie);
        findViewById(R.id.lin_collect).setOnClickListener(this);
        findViewById(R.id.lin_sign).setOnClickListener(this);
        mLinImgortext = (LinearLayout) findViewById(R.id.lin_imgortext);
        mLinImgortext.setOnClickListener(this);
        findViewById(R.id.ll_zifu).setOnClickListener(this);
        findViewById(R.id.ll_weixin).setOnClickListener(this);
        findViewById(R.id.tv_cancel).setOnClickListener(this);
        findViewById(R.id.tv_sign).setOnClickListener(this);
        loaderImage = new LoaderImage(this);

        listView = (RefreshListView) findViewById(R.id.listview);
    }

    @Override
    public void onClickEvent(View view) {
        switch (view.getId()) {
            case R.id.lin_collect:
                if (iscollect) {
                    presenter.collectCancle(hospitalId);
                } else {
                    presenter.collectdoctor(hospitalId);
                }
                break;
            case R.id.lin_sign:

                if ("1".equals(doctorDetail.getSign())) {
                    showToastMessage("你已签约");
                } else {
                    if ("0".equals(Token.getHasDoctor())) {
                        if (!"1".equals(doctorDetail.getIsSign())) {
                            showToastMessage("该医生暂未开通家庭医生服务");
                        } else {
                            WebSettings webSettings = webview.getSettings();
                            webSettings.setJavaScriptEnabled(true);
                            webview.loadUrl("http://app2.doudoutech.com/view/protocol.htm");
                            rel_sign.setVisibility(View.VISIBLE);
                        }
                    } else {
                        IsSignDialog isSignDialog = new IsSignDialog(this, new IsSignDialog.Issinglistener() {
                            @Override
                            public void Issing() {
                                if (!"1".equals(doctorDetail.getIsSign())) {
                                    showToastMessage("该医生暂未开通家庭医生服务");
                                } else {
                                    WebSettings webSettings = webview.getSettings();
                                    webSettings.setJavaScriptEnabled(true);
                                    webview.loadUrl("http://app2.doudoutech.com/view/protocol.htm");
                                    rel_sign.setVisibility(View.VISIBLE);
                                }
                            }
                        });
                        isSignDialog.show();
                    }
                }
                break;
            case R.id.lin_imgortext:
                ptype = "2";
                mLinImgortext.setEnabled(false);
                new Handler().postDelayed(new Runnable() {
                    public void run() {
                        mLinImgortext.setEnabled(true);
                    }
                }, 3000);
                singTextAndImg(ptype);
                break;
            case R.id.rel_zifufangsi:
//                mRlPay.setVisibility(View.GONE);
                break;
            case R.id.ll_zifu:
                zqtype = "1";
                prdId = prdetail.getPrdId();
                alltotal_fee = prdetail.getPrize();
                presenter.prdbuy(prdetail.getPrdId(), prdetail.getPrize(), ptype, zqtype, recId, doctorId, hospitalId);
                break;
            case R.id.ll_weixin:
                zqtype = "2";
                prdId = prdetail.getPrdId();
                alltotal_fee = prdetail.getPrize();
                presenter.prdbuy(prdetail.getPrdId(), prdetail.getPrize(), ptype, zqtype, recId, doctorId, hospitalId);
                break;
            case R.id.rel_sign:
                rel_sign.setVisibility(View.GONE);
                break;
            case R.id.tv_cancel:
                rel_sign.setVisibility(View.GONE);
                break;
            case R.id.tv_sign:
                rel_sign.setVisibility(View.GONE);
                ptype = "4";
                singdoctor(ptype);
                break;

            case R.id.img_call:
                ptype = "3";
//                singTextAndImg(ptype);
                //如果签约直接打电话   没有签约进入到打预约电话然后支付
                if ("1".equals(doctorDetail.getSign())) {
                    mImgCall.setEnabled(false);
                    new Handler().postDelayed(new Runnable() {
                        public void run() {
                            mImgCall.setEnabled(true);
                        }
                    }, 10000);
                    DiseaseListDialog diseaseListDialog = new DiseaseListDialog(this, litapals, new DiseaseListDialog.onItemClickListener() {
                        @Override
                        public void itemClick(int position) {
                            DiaeasesLitapal litapal = litapals.get(position);
                            String disname = litapal.getName();
                            String disid = litapal.getDisId();
//                        userId	String	是	用户id
//                        token	String	是	唯一标示
//                        reqType	String	是	1-医生拨打患者电话 2-患者拨打医生电话
//                        accId	String	是	云信id
//                        caller	String	是	主叫电话号码
//                        callee	String	是	被叫电话号码
//                        hosId	String	否	医生医院id reqType=2时用
//                        doctorId	String	否	医生id reqType=2时用
//                        diseId	String	否	病种id reqType=2时用
//                        recId	String	否	病历id reqType=1时用

                            presenter.getCalling(doctorDetail.getPhone(), hospitalId, doctorId, "", disid);
                        }

                        @Override
                        public void setfinis() {

                        }
                    });
                    diseaseListDialog.show();
                } else {
                    Intent intent = new Intent(DoctorDetailActivity.this, MakeCallActivity.class);
                    intent.putExtra("hosid", hospitalId);
                    intent.putExtra("doctorid", doctorId);
                    intent.putExtra("price", alltotal_fee);
                    intent.putExtra("accId", accId);
                    intent.putExtra("recId", recId);
                    startActivity(intent);
                }
                break;

        }
    }


    /**
     * 图文咨询
     *
     * @param ptype
     */

    private void singTextAndImg(String ptype) {
        getpayEnd();
    }

    /**
     * 签约医生
     *
     * @param ptype
     */
    private void singdoctor(String ptype) {
        //判断是否签约
        if ("1".equals(doctorDetail.getSign())) {
            showToastMessage("您已签约");
        } else {
            //如果没有签约就调用获取价格接口
            presenter.getprdetail(ptype);
        }
    }

    @Override
    public void setContentLayout() {
        setContentView(R.layout.activity_doctor_detail);
    }

    @Override
    public void getdoctordetail(DoctorDetail doctorDetail, List<DoctorEvaluate> doctorEvaluates) {
        if (doctorDetail != null) {
            this.doctorDetail = doctorDetail;
            doctorId = doctorDetail.getDoctorId();
            hospitalId = doctorDetail.getHospitalId();
            accId = doctorDetail.getAccId();

            loaderImage.load(headImage, doctorDetail.getHeadPic(), new ImageLoadingListener() {

                @Override
                public void onLoadingStarted(String s, View view) {
                    headImage.setImageResource(R.drawable.img_doctordefault);
                }

                @Override
                public void onLoadingFailed(String s, View view, FailReason failReason) {
                    headImage.setImageResource(R.drawable.img_doctordefault);
                }

                @Override
                public void onLoadingComplete(String s, View view, Bitmap bitmap) {

                }

                @Override
                public void onLoadingCancelled(String s, View view) {

                }
            });
            mTvName.setText(doctorDetail.getName() + "    " + doctorDetail.getPosition());
            String Evaluate = Util.isEmpty(doctorDetail.getEvaluate()) ? "100" : doctorDetail.getEvaluate();
            mTvEvaluate.setText("好评率：" + Evaluate + "%");
            String num = Util.isEmpty(doctorDetail.getSignNum()) ? "0" : doctorDetail.getSignNum();
            mTvSignnum.setText("签约数：" + num);
            mTvDist.setText(doctorDetail.getDistance() + "m");
            mTvAddress.setText(doctorDetail.getHospital());
            if ("1".equals(doctorDetail.getSign())) {
                mImgSign.setBackgroundResource(R.drawable.icon_sign);
                mTvSign.setText("已签约");
                mTvSign.setTextColor(getResources().getColor(R.color.main_color));

            } else {
                mImgSign.setBackgroundResource(R.drawable.icon_nosign);
                mTvSign.setText("签约");
                mTvSign.setTextColor(Color.parseColor("#888888"));

            }
            if ("1".equals(doctorDetail.getIsCollect())) {
                mImgCollect.setBackgroundResource(R.drawable.icon_collect);
                mTvCollect.setText("已收藏");
                mTvCollect.setTextColor(getResources().getColor(R.color.main_color));
                iscollect = true;
            } else {
                mImgCollect.setBackgroundResource(R.drawable.icon_nocollect);
                mTvCollect.setText("收藏");
                mTvCollect.setTextColor(Color.parseColor("#888888"));
                iscollect = false;
            }

            if ("1".equals(doctorDetail.getCallSwitch())) {//有电话
                mTvIsCall.setVisibility(View.VISIBLE);
                mImgCall.setVisibility(View.VISIBLE);
            } else {
                mTvIsCall.setVisibility(View.GONE);
                mImgCall.setVisibility(View.INVISIBLE);
            }
            if ("1".equals(doctorDetail.getIsSign())) {//是家庭医生
                mTvIsDoctor.setVisibility(View.VISIBLE);
            } else {
                mTvIsDoctor.setVisibility(View.GONE);
            }
            if ("1".equals(doctorDetail.getOnline())) {
                isonlie.setVisibility(View.GONE);
            } else {
                isonlie.setVisibility(View.VISIBLE);
            }
        }

        if (!Util.isEmpty(doctorEvaluates)) {
            mLlNoEvaluate.setVisibility(View.GONE);
            this.evaluates.clear();
            this.evaluates = doctorEvaluates;
            adapter.setData(evaluates);
            adapter.notifyDataSetChanged();
        } else {
            mLlNoEvaluate.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void getfail() {
        showToastMessage("加载失败");
    }

    @Override
    public void signSucced() {
        showToastMessage("签约成功");
        mImgSign.setBackgroundResource(R.drawable.icon_sign);
        mTvSign.setText("已签约");
        mTvSign.setTextColor(getResources().getColor(R.color.main_color));
        doctorDetail.setSign("1");
    }

    @Override
    public void signfail() {
        mImgSign.setBackgroundResource(R.drawable.icon_nosign);
        mTvSign.setText("签约");
        mTvSign.setTextColor(Color.parseColor("#888888"));
        SignFailDialog signFailDialog = new SignFailDialog(this, new SignFailDialog.ClickListener() {
            @Override
            public void Retry() {
                presenter.signdoctor(hospitalId, prdbuy.getPayId());
            }

            @Override
            public void Toreimburse() {
                Intent intent = new Intent(DoctorDetailActivity.this, UserConsumeActivity.class);
                startActivity(intent);
            }
        });
        signFailDialog.show();
    }

    @Override
    public void collectSucced() {
        showToastMessage("收藏成功");
        mImgCollect.setBackgroundResource(R.drawable.icon_collect);
        mTvCollect.setText("已收藏");
        mTvCollect.setTextColor(getResources().getColor(R.color.main_color));
        iscollect = true;
    }

    @Override
    public void collectfail() {
        showToastMessage("收藏失败");
        mImgCollect.setBackgroundResource(R.drawable.icon_nocollect);
        mTvCollect.setText("收藏");
        mTvCollect.setTextColor(Color.parseColor("#888888"));
        iscollect = false;
    }

    @Override
    public void getprdetail(Prdetail prdetail) {
        if (prdetail != null) {
            this.prdetail = prdetail;
            //判断价格是否大于0(如果大于0弹出支付方式否则调用下单接口)
            if (prdetail.getPrizes() <= 0) {
                isprice = false;
                presenter.prdbuy(prdetail.getPrdId(), prdetail.getPrize(), ptype, type, recId, doctorId, hospitalId);
            } else {
//                isprice = false;
//                presenter.prdbuy(prdetail.getPrdId(), prdetail.getPrize(), ptype, type, recId, doctorId, hospitalId);
                isprice = true;
                mRlPay.setVisibility(View.VISIBLE);
                mTvPrdName.setText(prdetail.getName() + "(" + prdetail.getPrize() + "元/次)");
                mTvPrdPirce.setText(prdetail.getPrize() + "元");
            }

        }
    }


    /**
     * create the order info. 创建订单信息
     */
    private String getOrderInfo(final Prdbuy prdbuy) {

        // 签约合作者身份ID
        String orderInfo = "partner=" + "\"" + prdbuy.getPartner() + "\"";

        // 签约卖家支付宝账号
        orderInfo += "&seller_id=" + "\"" + prdbuy.getSeller_id() + "\"";

        // 商户网站唯一订单号
        orderInfo += "&out_trade_no=" + "\"" + prdbuy.getOut_trade_no() + "\"";

        // 商品名称
        orderInfo += "&subject=" + "\"" + prdbuy.getSubject() + "\"";

//        // 商品详情
//        orderInfo += "&body=" + "\"" + prdbuy.getSubject() + "\"";

        // 商品金额
        orderInfo += "&total_fee=" + "\"" + prdbuy.getTotal_fee() + "\"";

        // 服务器异步通知页面路径
        orderInfo += "&notify_url=" + "\"" + prdbuy.getNotify_url() + "\"";

        // 服务接口名称， 固定值
        orderInfo += "&service=" + "\"" + prdbuy.getService() + "\"";

        // 支付类型， 固定值
        orderInfo += "&payment_type=" + "\"" + prdbuy.getPayment_type() + "\"";

        // 参数编码， 固定值
        orderInfo += "&_input_charset=" + "\"" + prdbuy.get_input_charset() + "\"";


        // 设置未付款交易的超时时间
        // 默认30分钟，一旦超时，该笔交易就会自动被关闭。
        // 取值范围：1m～15d。
        // m-分钟，h-小时，d-天，1c-当天（无论交易何时创建，都在0点关闭）。
        // 该参数数值不接受小数点，如1.5h，可转换为90m。
//        orderInfo += "&it_b_pay=\"30m\"";

        // extern_token为经过快登授权获取到的alipay_open_id,带上此参数用户将使用授权的账户进行支付
        // orderInfo += "&extern_token=" + "\"" + extern_token + "\"";

        // 支付宝处理完请求后，当前页面跳转到商户指定页面的路径，可空
//        orderInfo += "&return_url=\"m.alipay.com\"";

        // 调用银行卡支付，需配置此参数，参与签名， 固定值 （需要签约《无线银行卡快捷支付》才能使用）
        // orderInfo += "&paymethod=\"expressGateway\"";

        return orderInfo;
    }

    @Override
    public void getprdetailfail() {
        showToastMessage("请求失败");
    }

    @Override
    public void prdbuy(Prdbuy prdbuy, String ptype) {
        if (prdbuy != null) {
            this.prdbuy = prdbuy;
            if (isprice) {
//                zqtype  让我知道走的是微信的支付还是支付宝的支付
                if ("1".equals(zqtype)) {
                    pay(prdbuy);
                } else if ("2".equals(zqtype)) {
                    weixinpay(prdbuy);
                }
            } else {
                getpayEnd();
            }

        }
    }


    private void getpayEnd() {

//        2-图文咨询 3-电话咨询 4-签约医生
        if ("2".equals(ptype)) {
            presenter.getgoAndFrom(hospitalId);
        } else if ("3".equals(ptype)) {
            Intent intent = new Intent(DoctorDetailActivity.this, MakeCallActivity.class);
            intent.putExtra("hosid", hospitalId);
            intent.putExtra("doctorid", doctorId);
            intent.putExtra("price", alltotal_fee);
            intent.putExtra("accId", accId);
            intent.putExtra("recId", recId);
            startActivity(intent);
        } else if ("4".equals(ptype)) {
            presenter.signdoctor(hospitalId, prdbuy.getPayId());
        }
    }


    /**
     * 微信支付
     *
     * @param prdbuy
     */
    public void weixinpay(Prdbuy prdbuy) {
        PayReq req = new PayReq();
//        descr = {String@830056874488} "签约医生"
//        nonceStr = {String@830056797024} "1405122771"
//        notifyurl = {String@830035547520} "http://192.168.1.181:8080/doctor/pay/weipayresult.do"
//        partnerId = {String@830056775728} "1333270401"
//        payId = {String@830061191736} "S101461823512"
//        prepayId = {String@830056874664} "wx2016042814051254615850620047017099"
//        sign = {String@830061191960} "516164A67AADA2907B1BAB098E44BDE4"
//        timeStamp = {String@830056775544} "1461823512"
        if (api != null) {
            req.appId = ConstantValue.APP_ID;
            req.partnerId = prdbuy.getPartnerId();
            req.prepayId = prdbuy.getPrepayId();
            req.nonceStr = prdbuy.getNonceStr();
            req.timeStamp = prdbuy.getTimeStamp();
            req.packageValue = "Sign=WXPay";
            req.sign = prdbuy.getSign();
//            req.extData = "app data"; // optional
//            Toast.makeText(DoctorDetailActivity.this, "正常调起支付", Toast.LENGTH_SHORT).show();
            // 在支付之前，如果应用没有注册到微信，应该先调用IWXMsg.registerApp将应用注册到微信
            api.sendReq(req);
        }
    }


    public class PayOkRecedir extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if ("PayOkRecedir".equals(action)) {
                int code = intent.getIntExtra("code", -1);
                if (code == 0) {
                    presenter.paysuccess(type, prdbuy.getPayId());
                }
            }
        }
    }


    /**
     * call alipay sdk pay. 调用SDK支付
     */
    public void pay(final Prdbuy prdbuy) {

        String orderInfo = getOrderInfo(prdbuy);

        /**
         * 特别注意，这里的签名逻辑需要放在服务端，切勿将私钥泄露在代码中！
         */
        String sign = sign(orderInfo, prdbuy.getPrivateKey());
        try {
            /**
             * 仅需对sign 做URL编码
             */
            sign = URLEncoder.encode(sign, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        /**
         * 完整的符合支付宝参数规范的订单信息
         */
        final String payInfo = orderInfo + "&sign=\"" + sign + "\"&" + getSignType(prdbuy.getSign_type());

        Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                // 构造PayTask 对象
                PayTask alipay = new PayTask(DoctorDetailActivity.this);
                // 调用支付接口，获取支付结果
                String result = alipay.pay(payInfo, true);

                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };

        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    /**
     * sign the order info. 对订单信息进行签名
     *
     * @param content 待签名订单信息
     */
    private String sign(String content, String privateKey) {
        return SignUtils.sign(content, privateKey);
    }

    /**
     * get the sign type we use. 获取签名方式
     */
    private String getSignType(String sign_type) {
        return "sign_type=" + "\"" + sign_type + "\"";
    }


    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    PayResult payResult = new PayResult((String) msg.obj);
                    /**
                     * 同步返回的结果必须放置到服务端进行验证（验证的规则请看https://doc.open.alipay.com/doc2/
                     * detail.htm?spm=0.0.0.0.xdvAU6&treeId=59&articleId=103665&
                     * docType=1) 建议商户依赖异步通知
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息

                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
                    if (TextUtils.equals(resultStatus, "9000")) {
                        presenter.paysuccess(type, prdbuy.getPayId());
                    } else {
                        // 判断resultStatus 为非"9000"则代表可能支付失败
                        // "8000"代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
                        if (TextUtils.equals(resultStatus, "8000")) {
                            Toast.makeText(DoctorDetailActivity.this, "支付结果确认中", Toast.LENGTH_SHORT).show();

                        } else {
                            // 其他值就可以判断为支付失败，包括用户主动取消支付，或者系统返回的错误
                            Toast.makeText(DoctorDetailActivity.this, "支付失败", Toast.LENGTH_SHORT).show();

                        }
                    }
                    break;
                }
                default:
                    break;
            }
        }

    };

    @Override
    public void prdbuyfail() {
        showToastMessage("请求失败");
    }

    @Override
    public void cancelcollect() {
        showToastMessage("取消收藏成功");
        mImgCollect.setBackgroundResource(R.drawable.icon_nocollect);
        mTvCollect.setText("收藏");
        mTvCollect.setTextColor(Color.parseColor("#888888"));
        iscollect = false;
    }

    @Override
    public void cancelcollectfail() {
        showToastMessage("请求失败");
        iscollect = true;
    }

    @Override
    public void IntentInquiryActivity(final String isCmp) {
        DiseaseListDialog diseaseListDialog = new DiseaseListDialog(this, litapals, new DiseaseListDialog.onItemClickListener() {
            @Override
            public void itemClick(int position) {
                DiaeasesLitapal litapal = litapals.get(position);
                String disname = litapal.getName();
                String disid = litapal.getDisId();
                Intent intent = new Intent(DoctorDetailActivity.this, InquiryActivity.class);
                intent.putExtra("disname", disname);
                intent.putExtra("disid", disid);
                intent.putExtra("doctorId", doctorId);
                intent.putExtra("hosId", hospitalId);
                intent.putExtra("isCmp", isCmp);
                intent.putExtra("accId", accId);
                intent.putExtra("sign", doctorDetail.getSign());
                intent.putExtra("name", doctorDetail.getName());
                startActivity(intent);
            }

            @Override
            public void setfinis() {

            }
        });
        diseaseListDialog.show();
    }

    @Override
    public void IntentP2PActivity(String recId, String status) {
        //Todo hosId医生医院id和recId问诊表id   //doctorid医院的ID    accId聊天人的云信ID
        SessionHelper.startP2PSession(this, accId, status, recId, hospitalId, Token.getId(), Token.getToken(), doctorId, accId, doctorDetail.getName(), doctorDetail.getSign());
    }

    @Override
    public void IntentP2PActivityGo() {

    }

    @Override
    public void IntentP2PActivityTwo() {

    }

    @Override
    public void getdoctorfail() {
        showToastMessage("加载失败");
    }

    @Override
    public void paysuccess() {
        mRlPay.setVisibility(View.GONE);
        if ("4".equals(ptype)) {
            SharedPreferencesUtils.setParam(DoctorDetailActivity.this, "isSignDoctorid", doctorId);
        }
//        Toast.makeText(DoctorDetailActivity.this, "支付成功", Toast.LENGTH_SHORT).show();
        getpayEnd();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (mRlPay.getVisibility() == View.VISIBLE) {
                mRlPay.setVisibility(View.GONE);
            } else {
                finish();
            }
        }
        return true;
    }
}
